package com.tsfyun.scm.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.tsfyun.common.base.extension.OrderItem;
import com.tsfyun.common.base.util.StringUtils;
import com.tsfyun.scm.system.dto.LevyDutiesDTO;
import com.tsfyun.scm.system.entity.LevyDuties;
import com.tsfyun.scm.system.mapper.LevyDutiesMapper;
import com.tsfyun.scm.system.service.ILevyDutiesService;
import com.tsfyun.common.base.extension.ServiceImpl;
import com.tsfyun.scm.system.util.TsfWeekendSqls;
import com.tsfyun.scm.system.vo.LevyDutiesVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  加征关税服务实现类
 * </p>
 *

 * @since 2020-03-20
 */
@Service
public class LevyDutiesServiceImpl extends ServiceImpl<LevyDuties> implements ILevyDutiesService {

    @Autowired
    private LevyDutiesMapper levyDutiesMapper;

    @Override
    public PageInfo<LevyDuties> page(LevyDutiesDTO dto) {
        TsfWeekendSqls sqls = TsfWeekendSqls.<LevyDuties>custom()
                .andLike(true, LevyDuties::getHsCode,dto.getHsCode())
                .andEqualTo(true,LevyDuties::getIsStart,dto.getIsStart());
        return super.pageList(dto.getPage(),dto.getLimit(),sqls, Lists.newArrayList(OrderItem.asc("hsCode")));
    }

    @Override
    public Map<String, List<LevyDutiesVO>> listByHsCodes(List<String> hsCodes) {
        List<LevyDuties> list = levyDutiesMapper.selectByExample(Example.builder(LevyDuties.class).where(TsfWeekendSqls.<LevyDuties>custom()
                        .andIn(false,LevyDuties::getHsCode,hsCodes)).build());
        if(CollUtil.isEmpty(list)) {
            return null;
        }
        List<LevyDutiesVO> levyDutiesVOS = beanMapper.mapAsList(list,LevyDutiesVO.class);
        return levyDutiesVOS.stream().collect(Collectors.groupingBy(LevyDutiesVO::getHsCode));
    }

    @Override
    public BigDecimal taxByHsCode(String hsCode) {
        if(StringUtils.isEmpty(hsCode)){
            return null;
        }
        LevyDuties levyDuties = new LevyDuties();
        levyDuties.setCountryCode("USA");
        levyDuties.setIsStart(Boolean.TRUE);
        levyDuties.setHsCode(hsCode);
        List<LevyDuties> levyDutiesList =  super.list(levyDuties);
        if(CollUtil.isNotEmpty(levyDutiesList)){
            return levyDutiesList.get(0).getLevyVal();
        }
        return null;
    }
}
